/**
 * 认证服务
 */
angular
.module('myApp')
.factory('tokenManager', function($window) {

  var storageName = 'token';

  return {
    setToken: function(accessToken, expire) {
      var expireAt = new Date();
          expireAt.setSeconds(expireAt.getSeconds() + expire);

      var params = {
        access_token: accessToken,
        expire_at: expireAt
      };

      $window.localStorage.setItem(storageName, JSON.stringify(params));
    },
    getToken: function() {
      var tokenify = $window.localStorage.getItem(storageName);

      if (null === tokenify) {
        return false;
      }

      var token = JSON.parse(tokenify);

      var date        = new Date();
      var dateExpire  = new Date(token.expire_at);

      if (date.getTime() > dateExpire.getTime()) {
        this.clearToken();
        return false;
      }

      return token;
    },
    clearToken: function() {
      $window.localStorage.removeItem(storageName);
    }
  }
});
